/**
 * 获取地址栏参数
 * 
 * @param name
 * @returns
 */
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null)
		return decodeURIComponent(r[2]);
	return null;
}

function getParentUrlParam(name) {

	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = parent.location.search.substr(1).match(reg);
	if (r != null)
		return decodeURIComponent(r[2]);
	return null;
}

$.fn.serializeJson = function() {
	var serializeObj = {};
	$(this.serializeArray()).each(
			function() {
				if (serializeObj[this.name] != undefined) {
					if ($.isArray(serializeObj[this.name])) {
						serializeObj[this.name].push(this.value);
					} else {
						serializeObj[this.name] = [ serializeObj[this.name],
								this.value ];
					}
				} else {
					serializeObj[this.name] = this.value;
				}
			});
	return serializeObj;
};

function getRootPath() {
	// 获取当前网址，如： http://localhost:8083/proj/meun.jsp
	var curWwwPath = window.document.location.href;
	// 获取主机地址之后的目录，如： proj/meun.jsp
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	// 获取主机地址，如： http://localhost:8083
	var localhostPath = curWwwPath.substring(0, pos);
	// 获取带"/"的项目名，如：/proj
	var projectName = pathName
			.substring(0, pathName.substr(1).indexOf('/') + 1);
	return (localhostPath + projectName);
}

/**
 * 检查手机号码
 * 
 * @param phone
 * @returns
 */
function checkPhone(phone) {
	var reg = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-9]))[0-9]{8}$/;
	return reg.test(phone);
}

function isPhoneAvailable(phone) {
	return checkPhone(phone);
}

/**
 * 检查邮箱地址
 * 
 * @param email
 * @returns
 */
function checkEmail(email) {
	var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return reg.test(email);
}

/**
 * 检查文件格式
 * 
 * @param filename
 *            文件名称
 */
function checkFileExt(filename) {
	var flag = false; // 状态
	var arr = [ "jpg", "png", "jpeg" ];
	// 获取上传文件的扩展名
	var index = filename.lastIndexOf(".");
	var ext = filename.substr(index + 1).toLowerCase();
	var length = arr.length;
	for (var i = 0; i < length; i++) {
		if (ext == arr[i]) {
			flag = true;
			break;
		}
	}
	return flag;
}

/**
 * 检查文件是否小于5mb
 * 
 * @param file
 * @returns
 */
function lessMaxSize(file) {
	var MAXSIZE = 5; // 单位为mb
	var size = file.size; // byte
	size = size / 1024; // kb
	size = size / 1024; // mb
	if (size > MAXSIZE) {
		return false;
	} else {
		return true;
	}
}

String.prototype.startWith = function(str) {
	var reg = new RegExp("^" + str);
	return reg.test(this);
}

String.prototype.endWith = function(str) {
	var reg = new RegExp(str + "$");
	return reg.test(this);
}

CanvasRenderingContext2D.prototype.wrapText = function(text, x, y, maxWidth,
		lineHeight) {
	if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
		return;
	}

	var context = this;
	var canvas = context.canvas;

	if (typeof maxWidth == 'undefined') {
		maxWidth = (canvas && canvas.width) || 300;
	}
	if (typeof lineHeight == 'undefined') {
		lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight))
				|| parseInt(window.getComputedStyle(document.body).lineHeight);
	}

	// 字符分隔为数组
	var arrText = text.split('');
	var line = '';

	for (var n = 0; n < arrText.length; n++) {
		var testLine = line + arrText[n];
		var metrics = context.measureText(testLine);
		var testWidth = metrics.width;
		if (testWidth > maxWidth && n > 0) {
			context.fillText(line, x, y);
			line = arrText[n];
			y += lineHeight;
		} else {
			line = testLine;
		}
	}
	context.fillText(line, x, y);
};

/**
 * 检查屏幕宽度
 * 
 * @returns
 */
function isPhoneScreen() {
	var width = window.screen.width;
	var isPhone = false;
	if (width < 601) {
		isPhone = true;
	}
	return isPhone;
}

function plusXing(str, frontLen, endLen) {
	var len = str.length - frontLen - endLen;
	var xing = '';
	for (var i = 0; i < len; i++) {
		xing += '*';
	}
	return str.substring(0, frontLen) + xing
			+ str.substring(str.length - endLen);
}

function getParam(url, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	if(url.split("?").length == 1) {
		return null;
	}
	var r = url.split("?")[1].match(reg);
	if (r != null) {
		return decodeURIComponent(r[2]);		
	}
	return null;
}

function isNull(str) {
	var isNull = false;
	if (str == '' || $.trim(str).length == 0) {
		isNull = true;
	}
	return isNull;
}
var isPhone = isPhoneScreen();
// header 常用应用的事件 props（是否手机，触发事件的id）///////////////////////////////////////////
function headerMenuShow(navId) {
	var rootPath = getRootPath();

	var navId = navId;
	$("<link>").attr({
		rel : "stylesheet",
		type : "text/css",
		href : rootPath + "/normal/js/common/headerUtil.css"
	}).appendTo("head");

	// 隐藏的常用应用
	var html = '<div class="normal">'
			+ '<label class="title">常用应用</label> <label class="line"></label>'
			+ '<ul>' + '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/NC@2x.png"></li>'
			+ '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/MIS@2x.png"></li>'
			+ '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/FW@2x.png"></li>'
			+ '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/BOX@2x.png"></li>'
			+ '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/LX@2x.png"></li>'
			+ '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/course@2x.png"></li>'
			+ '<li><img alt="" src="'
			+ rootPath
			+ '/normal/images/logo/fire@2x.png"></li>'
//			+ '<li><span>全部</span></li>' 
			+ '</ul>' + '</div>';
	$("body").append('<div class="mask"></div>');
	
	if(!isPhone){
		$("#naviWrapper").append(html);
	}else{
		$("body").append(html);
		$(".mask").css("z-index","999");
	}
	$(".normal").hide();
	$(".mask").hide();
	if (!isPhone) {
		navId.hover(function() {
			$(".mask").show();
			$(".normal").show();
			$(".normal").hover(function(){
				$(this).show();
				$(".mask").show();
			},function(){
				$(this).hide();
				$(".mask").hide();
			})
		})

		$(".mask").on("click", function() {
			$(".normal").hide();
			$(this).hide();
		});

	} else {
		navId.click(function() {
			if(navId.hasClass("nav-show")){
				navId.removeClass("nav-show");
				$(".normal").hide();
				$(".mask").hide();
			}else{
				navId.addClass("nav-show");
				$(".normal").show();
				$(".mask").show();
			}
		})
		$(".mask").click(function() {
			$(this).hide();
			$(".normal").hide();
		})
	}

}
// ///////////////////////////////////////////////////////////////////////////////////////
function login_reg(id) {
	var rootPath = getRootPath();
	$("<link>").attr({
		rel : "stylesheet",
		type : "text/css",
		href : rootPath + "/normal/js/common/headerUtil.css"
	}).appendTo("head");
	var id = id;
	var html = '<div class="reg"><span class="login_btn">登录</span> | <span class="reg_btn">注册</span></div>';
	id.append(html);
	$(".reg_btn").click(function() {
		var url = rootPath + "/normal/pages/guest/reg.html";
		document.location.href = url;
	});
	// 5.登录按钮
	$(".login_btn").click(function() {
		var url = rootPath + "/normal/pages/guest/login.html";
		document.location.href = url;
	});
	// 如果登录 获取用户的头像 替换注册/登录 Ajax请求
	$.ajax({
		url : rootPath + '/user/queryUserself',
		type : 'GET',
		contentType : 'application/json;charset=UTF-8',
		success : function(data) {
			if (data.returnCode == '0000') {
				var user = data.returnObject;
				var html = '';
				if (user != null && user.headimgurl != null
						&& user.headimgurl != '') {
					html = '<img class="headerImg" id="operate" src="'
						+ rootPath + '/file/viewimg?fileName='
						+ (user.headimgurl) + '&type=1' + '" alt=""/>';
				} else {
					html = '<img class="headerImg" id="operate" src="'
							+ rootPath + '/normal/images/operate.png"  alt=""/>'
				}
				$(".reg").hide();
				id.append(html);
				$(".headerImg").click(function() {
					var url = rootPath + "/normal/pages/member/menu.html";
					document.location.href = url;

				})
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			layer.alert("error");
		}
	});
}

/**
 * 切换页面
 * @param creType  认证类别
 * @returns
 */
function switchPage(creType,rleId) {
	var regex = /^[0-9]*$/;
	if(!regex.test(creType)) {
		layer.alert("跳转页面出错,请求参数有误:)");
		return;
	}
	var url;
	var urlSuffix = "?rleId=" + rleId;
	switch(parseInt(creType)) {
	case 1:
		url = 'teacherAuth.html';
		break;
	case 2:
		url = 'volAuth.html';
		break;
	case 3:
		url = '';
		break;
	case 4:
		url = 'coachPlanAuth.html';
		break;
	case 5:
		url = 'studentAuth.html';
		break;
	case 6:  //去远方教师
	case 7:  //去远方学生
	case 8:  //去远方出行志愿者
	case 9:  //去远方评审志愿者
		url = 'goFarAwayAuth.html';
		break;
	case 10: //社区认证 /社区梦想中心
	case 20: //乡镇版社区认证 
		url = 'adreamCenter.html';
		break;
	case 11:  	//教练计划
	case 12:   //教练计划
	case 13:   //教练计划
	case 14:   //教练计划
		url = 'coachPlanAuth.html';
		break;
	case 15:   //运动梦想课
		url = 'sportsClassAuth.html';
		break;
	case 16:   //校长训练营-校长
	case 17:   //校长训练营-讲师/助教
	case 18:   //校长训练营-示范课老师
		url = 'htcAuth.html';
		break;
	case 19:   //卓越梦想校长报名
		url = 'excellenceAdreamHeadMasterEnrollAuth.html';
		break;
	case 101:
		url = 'businessAuth.html';
		break;
	case 102:
		url = 'govAuth.html';
		break;
	case 103:
		url = 'orgAuth.html';
		break;
	case 104:
		url = 'specialFundAuth.html';
		break;
	case 105:
		url = 'publicWelfareTeam.html';
		break;
	}
	url += urlSuffix;
	return url;
}

/**
 * "身份认证"根据排序值获取认证方式
 * @param sort  排序值
 * @returns {String}  认证方式
 */
function getTitle(sort) {
	var regex = /^[0-9]*$/;
	if(!regex.test(sort)) {
		layer.alert("操作失败,请求参数有误:)");
		return;
	}
	var title;
	switch(parseInt(sort)) {
	case 1:
		title = '梦想教师认证';
		break;
	case 2:
		title = '志愿者认证';
		break;
	case 3:
		title = '基金会员工认证';
		break;
	case 4:
		title = '教练计划认证';
		break;
	case 5:
		title = '学生认证';
		break;
	case 6:
	case 7:
	case 8:
	case 9:
		title = '去远方认证';
		break;
	case 10:
	case 20:
		title = '社区认证';
		break;
	case 11:
	case 12:
	case 13:
	case 14:
		title = '教练计划认证';
		break;
	case 15:
		title = '运动梦想课认证';
		break;
	case 16:    
	case 17:    
	case 18:    
		title = '校长训练营认证';
		break;
	case 19:
		title = '卓越梦想校长报名';
		break;
	case 101:
		title = '企业认证';
		break;
	case 102:
		title = '政府认证';
		break;
	case 103:
		title = '社会组织认证';
		break;
	case 104:
		title = '专项基金认证';
		break;
	case 105:
		title = '公益团队认证';
		break;
	}
	return title;
}

//显示loading
function showLoading() {
	parent.$("#content").showLoading();
}

//隐藏loading
function hideLoading() {
	parent.$("#content").hideLoading();
}

//
function showLoadingById(id) {
	$("#" + id).showLoading();
}

//解决苹果手机登录、注册、绑定微信页面的触发input输入框焦点  页面放大问题
function banTouches(){
	document.addEventListener('touchstart',function(e){
		    //touchstart:触摸开始的一瞬间，这里的e包含的触摸一瞬间所触摸的元素的信息
			if(e.touches.length>1){
				e.preventDefault();
			}
		},false);
		var lastTouchEnd = 0;
		document.addEventListener('touchend',function(e){
		    //touchend:触摸结束的一瞬间，这里的e没有多大的作用
			var now = (new Date()).getTime();
			if(now-lastTouchEnd<=300){
				e.preventDefault();
			 }
			lastTouchEnd = now;
		},false);

}

/**根据url和参数名称获取入口:暂用于'神策数据'
 * @param url
 * @param name
 * @returns {String}
 */
function getEntranceByUrlAndUrlParam(url,name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	if(url.split("?").length == 1) {
		return "统一账户";
	}
	var r = url.split("?")[1].match(reg);
	var value;
	if (r != null) {
		value = decodeURIComponent(r[2]);
	} else {
		return "其他";
	}
	//根据域名进行获取
	if(value.indexOf("account") != -1) {
		return "统一账户";
	} else if(value.indexOf("activity") != -1) {
		return "真爱活动"
	} else if(value.indexOf("task") != -1) {
		return "任务系统"
	} else if(value.indexOf("wenku") != -1) {
		return "梦想文库"
	} else if(value.indexOf("coursecenter") != -1) {
		return "梦想课程"
	} else if(value.indexOf("adreambox") != -1) {
		return "梦想盒子"
	} else if(value.indexOf("edu") != -1) {
		return "真爱云学院"
	} else {
		return "其他";
	}
}

function formatUndefined(data) {
	return data == undefined ? "" : data;
}